using B.S.Data.MES.API.Applications.BaseData.Command.ProductMaterialCommand;
using B.S.Domain.BasicData.MaterialManagement.Product_material;
using B.S.Domain.Dto.WuLiaoDto;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using B.S.Domain.BasicData.MaterialManagement.MaterialGroups;
using B.S.Domain.BasicData.MaterialManagement.Material_type;
using B.S.Domain.Process.ProcessrouteName;

namespace B.S.Data.MES.API.Applications.BaseData.CommandHandlers.ProductMaterialCommandHandlers
{
    public class QueryProductMaterialCommandHandler : IRequestHandler<QueryProductMaterialCommand, APIRequst<APIPageing<List<ProductMaterialDto>>>>
    {
        private readonly IBaseRepository<Product_material> _productMaterialRepository;
        private readonly IBaseRepository<Material_group> _materialGroupRepository;
        private readonly IBaseRepository<Material_type> _materialTypeRepository;
        private readonly IBaseRepository<Processroute> _processrouteRepository;

        public QueryProductMaterialCommandHandler(
            IBaseRepository<Product_material> productMaterialRepository,
            IBaseRepository<Material_group> materialGroupRepository,
            IBaseRepository<Material_type> materialTypeRepository,
            IBaseRepository<Processroute> processrouteRepository)
        {
            _productMaterialRepository = productMaterialRepository;
            _materialGroupRepository = materialGroupRepository;
            _materialTypeRepository = materialTypeRepository;
            _processrouteRepository = processrouteRepository;
        }

        public Task<APIRequst<APIPageing<List<ProductMaterialDto>>>> Handle(QueryProductMaterialCommand request, CancellationToken cancellationToken)
        {
            // 使用LINQ实现四表连接查询，产品物料表为主表
            var query = from pm in _productMaterialRepository.GetAll()
                        join mg in _materialGroupRepository.GetAll() on pm.Grouptype equals mg.MaterId into materialGroupJoin
                        from mg in materialGroupJoin.DefaultIfEmpty()
                        join mt in _materialTypeRepository.GetAll() on mg.Materialtypeid equals mt.Materialtypeid into materialTypeJoin
                        from mt in materialTypeJoin.DefaultIfEmpty()
                        join pr in _processrouteRepository.GetAll() on pm.processroute equals pr.Id into processrouteJoin
                        from pr in processrouteJoin.DefaultIfEmpty()
                        select new ProductMaterialDto
                        {
                            Productid = pm.Productid,
                            Productcode = pm.Productcode,
                            ProductName = pm.ProductName,
                            specifications = pm.specifications,
                            unit = pm.unit,
                            Earlywarningvalue = pm.Earlywarningvalue,
                            Grouptype = pm.Grouptype,
                            processroute = pm.processroute,
                            describe = pm.describe,
                            CreateName = pm.CreateName,
                            UpdateTime = pm.UpdateTime,
                            MaterialGroupName = mg.Materialname,
                            MaterialType = mt.MaterialtypeName,
                            ProcessrouteName = pr.ProcessrouteName
                        };

            // 排序、分页
            var data = query.OrderByDescending(m => m.Productid)
                .Skip((request.Pageindex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToList();

            // 计算总数
            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / request.PageSize);

            // 构造分页结果
            APIPageing<List<ProductMaterialDto>> pageResult = new APIPageing<List<ProductMaterialDto>>
            {
                TotalCount = totalCount,
                Total = totalPages,
                Data = data
            };

            return Task.FromResult(new APIRequst<APIPageing<List<ProductMaterialDto>>> {
                Code = RequstCode.成功,
                Msg = RequstCode.成功.ToString(),
                Data = pageResult
            });
        }
    }
}